package com.hmall.common.interceptor;

import cn.hutool.core.util.ObjUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor implements HandlerInterceptor {

    public static final String USER_INFO = "user-info";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取user-info
        Long userInfo = Long.valueOf(request.getHeader(USER_INFO));
        // 将user-info放入UserContext中
        if (ObjUtil.isNotEmpty(userInfo)) {
            UserContext.setUser(userInfo);
        }
        // 放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理完毕后，清空UserContext
        UserContext.removeUser();
    }
}
